/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CadastroUsuario.java
 *
 * Created on 29/07/2009, 12:50:20
 */
package br.di0.nyx.cadastro;

import br.di0.sql.consulta.ConsultaUserDialog;
import br.di0.sql.insert.InsertUsuarios;
import br.di0.uteis.MetodosUteis;
import br.di0.uteis.MyOwnFocusTraversalPolicy;
import java.awt.Component;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import strategy.IDocument;
import strategy.concretas.DocLetras;
import strategy.concretas.DocNumeros;

/**
 *
 * @since 2009.08.17
 * @author di0
 */
public class CadastroUsuario extends javax.swing.JInternalFrame implements CadastroFrame {

    /** Creates new form CadastroUsuario */
    public CadastroUsuario(String titulo) {
        initComponents();
        this.setTitle(titulo);
        focusCicle();
        utils.setEnterHowNextTraversalKey(contentsPanel);
        limitarCampos();
    }

    /**
     * Aplica Expressões Regulares em JTextFields da janela
     */
    public void limitarCampos() {
        doc = new DocNumeros(5);
        codTextField.setDocument(doc.getDocumentoPlano());
        doc = new DocLetras(20);
        nomeTextField.setDocument(doc.getDocumentoPlano());
    }

    /**
     * Define o ciclo de foco nos itens da janela.
     */
    public void focusCicle() {
        order = new Vector<Component>(10);
        if (!novoCheckBox.isSelected()) {
            order.add(codTextField);
            order.add(buscaCodButton);
        }
        order.add(novoCheckBox);
        order.add(nomeTextField);
        order.add(resetSenhaButton);

        order.add(salvarButton);
        order.add(cancelarButton);

        newPolicy = new MyOwnFocusTraversalPolicy(order);
        this.setFocusTraversalPolicy(newPolicy);
    }

    /**
     * Limpa os campos da janela.
     */
    public void limparTela() {
        utils.limparCampos(contentsPanel);
        if (novoCheckBox.isSelected()) {
            nomeTextField.requestFocus();
        } else {
            codTextField.setEnabled(true);
            codTextField.requestFocus();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        comandosPanel = new javax.swing.JPanel();
        salvarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        contentsPanel = new javax.swing.JPanel();
        codLabel = new javax.swing.JLabel();
        codTextField = new javax.swing.JTextField();
        buscaCodButton = new javax.swing.JButton();
        novoCheckBox = new javax.swing.JCheckBox();
        nomeLabel = new javax.swing.JLabel();
        nomeTextField = new javax.swing.JTextField();
        cadastroLabel = new javax.swing.JLabel();
        cadastroTextField = new javax.swing.JTextField();
        resetSenhaButton = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);

        comandosPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        comandosPanel.setLayout(new java.awt.GridLayout(1, 0));

        salvarButton.setMnemonic('S');
        salvarButton.setText("Salvar");
        salvarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salvarButtonActionPerformed(evt);
            }
        });
        comandosPanel.add(salvarButton);

        cancelarButton.setMnemonic('C');
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });
        comandosPanel.add(cancelarButton);

        getContentPane().add(comandosPanel, java.awt.BorderLayout.PAGE_END);

        codLabel.setText("Código");

        codTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                codTextFieldFocusLost(evt);
            }
        });

        buscaCodButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/di0/icones/lupa16x16.png"))); // NOI18N
        buscaCodButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buscaCodButtonActionPerformed(evt);
            }
        });

        novoCheckBox.setMnemonic('N');
        novoCheckBox.setText("Novo");
        novoCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                novoCheckBoxActionPerformed(evt);
            }
        });

        nomeLabel.setText("Nome");

        cadastroLabel.setText("Data Cadastro");

        cadastroTextField.setEditable(false);
        cadastroTextField.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        cadastroTextField.setEnabled(false);
        cadastroTextField.setFocusable(false);

        resetSenhaButton.setMnemonic('R');
        resetSenhaButton.setText("Redefinir Senha");
        resetSenhaButton.setName("1"); // NOI18N
        resetSenhaButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetSenhaButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout contentsPanelLayout = new javax.swing.GroupLayout(contentsPanel);
        contentsPanel.setLayout(contentsPanelLayout);
        contentsPanelLayout.setHorizontalGroup(
            contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(contentsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, contentsPanelLayout.createSequentialGroup()
                        .addComponent(cadastroLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cadastroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(contentsPanelLayout.createSequentialGroup()
                        .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(codLabel)
                            .addComponent(nomeLabel))
                        .addGap(12, 12, 12)
                        .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(contentsPanelLayout.createSequentialGroup()
                                .addComponent(codTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(buscaCodButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(novoCheckBox))
                            .addComponent(nomeTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 285, Short.MAX_VALUE)))
                    .addComponent(resetSenhaButton, javax.swing.GroupLayout.DEFAULT_SIZE, 341, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        contentsPanelLayout.setVerticalGroup(
            contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(contentsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(codLabel)
                    .addComponent(buscaCodButton, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(novoCheckBox)
                    .addComponent(codTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nomeLabel)
                    .addComponent(nomeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(resetSenhaButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(contentsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cadastroTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cadastroLabel))
                .addContainerGap())
        );

        getContentPane().add(contentsPanel, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void salvarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarButtonActionPerformed
        String nome = nomeTextField.getText();
        if (novoCheckBox.isSelected()) {
            inserir(nome);
        } else {
            String cod_usuario = codTextField.getText();
            atualizar(cod_usuario, nome);
        }
}//GEN-LAST:event_salvarButtonActionPerformed

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        novoCheckBox.setSelected(false);
        codTextField.setEnabled(true);
        buscaCodButton.setEnabled(true);
        codTextField.requestFocus();
        limparTela();
        focusCicle();
}//GEN-LAST:event_cancelarButtonActionPerformed

    private void novoCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_novoCheckBoxActionPerformed
        ativaCodigo(codTextField, !novoCheckBox.isSelected());
        limparTela();
        focusCicle();
}//GEN-LAST:event_novoCheckBoxActionPerformed

    private void resetSenhaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetSenhaButtonActionPerformed
        String cod_usuario = codTextField.getText();
        String nome = nomeTextField.getText();
        if (!cod_usuario.equals("") && nome.length() > 0) {
            int result = InsertUsuarios.atualizar(cod_usuario, nome, null); //resetar senha
            if (result == 1) {
                JOptionPane.showMessageDialog(null, "Senha redefinida para " +
                        "o usuário [" + nome + "]. Uma nova senha será " +
                        "solicitada no próximo login.", "Cadastro de Usuário",
                        JOptionPane.INFORMATION_MESSAGE);
                limparTela();
            }
        } else {
            JOptionPane.showMessageDialog(null, "Não foi possível localizar o usuário.",
                    "Cadastro de Usuários", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_resetSenhaButtonActionPerformed

    private void codTextFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_codTextFieldFocusLost
        Component comp = evt.getOppositeComponent();
        if (comp != null) {
            if (comp.getName() == null) {
                carregarUsuario();
            }
        }
    }//GEN-LAST:event_codTextFieldFocusLost

    private void buscaCodButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscaCodButtonActionPerformed
        ConsultaUserDialog user = new ConsultaUserDialog(null, true, this);
        user.setVisible(true);
    }//GEN-LAST:event_buscaCodButtonActionPerformed

    private void inserir(String nome) {
        if (!nome.equals("")) {
            int result = InsertUsuarios.inserir(nome, null); // inserir no banco
            if (result == 1) {
                JOptionPane.showMessageDialog(null, "Usuário [" + nome +
                        "] cadastrado com sucesso.", "Cadastro de Usuário",
                        JOptionPane.INFORMATION_MESSAGE);
                limparTela();
            } else if (result == InsertUsuarios.ERROR_UNIQUE) {
                JOptionPane.showMessageDialog(null, "Já existe um usuário com este nome.",
                        "Cadastro de Usuário", JOptionPane.WARNING_MESSAGE);
                nomeTextField.requestFocus();
                nomeTextField.selectAll();
            } else {
                JOptionPane.showMessageDialog(null, "Não foi possivel cadastrar usuário.",
                        "Cadastro de Usuário", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(null, "Digite um nome para o usuário.",
                    "Cadastro de Usuário", JOptionPane.WARNING_MESSAGE);
            nomeTextField.requestFocus();
            nomeTextField.selectAll();
        }
    }

    private void atualizar(String cod_usuario, String nome) {
        if (!cod_usuario.equals("")) {
            if (!nome.equals("")) {
                int result = InsertUsuarios.atualizar(cod_usuario, nome, "0"); //atualizar banco
                if (result == 1) {
                    JOptionPane.showMessageDialog(null, "Usuário [" + nome +
                            "] alterado com sucesso.", "Cadastro de Usuário",
                            JOptionPane.INFORMATION_MESSAGE);
                    limparTela();
                } else if (result == InsertUsuarios.ERROR_UNIQUE) {
                    JOptionPane.showMessageDialog(null, "Já existe um usuário com este nome.",
                            "Cadastro de Usuário", JOptionPane.WARNING_MESSAGE);
                    nomeTextField.requestFocus();
                    nomeTextField.selectAll();
                } else if (result == InsertUsuarios.ERROR_ID_NOT_FOUND) {
                    JOptionPane.showMessageDialog(null, "Código não encontrado.",
                            "Cadastro de Usuário", JOptionPane.ERROR_MESSAGE);
                    codTextField.requestFocus();
                    codTextField.selectAll();
                } else {
                    JOptionPane.showMessageDialog(null, "Não foi possivel cadastrar usuário.",
                            "Cadastro de Usuário", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Digite um nome para o usuário.",
                        "Cadastro de Usuário", JOptionPane.WARNING_MESSAGE);
                nomeTextField.requestFocus();
                nomeTextField.selectAll();
            }
        } else {
            JOptionPane.showMessageDialog(null, "Digite um código válido.",
                    "Cadastro de Usuário", JOptionPane.WARNING_MESSAGE);
            codTextField.requestFocus();
            codTextField.selectAll();
        }
    }

    /**
     * Controle do JCheckBox novo.
     * @param codigoField o campo JTextField referente ao código.
     * @param desativar o status
     */
    public void ativaCodigo(JTextField codigoField, boolean desativar) {
        codigoField.setEnabled(desativar);
        if (!codigoField.isEnabled()) {
            codigoField.setText("");
        }
        buscaCodButton.setEnabled(desativar);
        resetSenhaButton.setEnabled(desativar);
    }

    private void carregarUsuario() {
        String cod_usuario = codTextField.getText();
        if (!cod_usuario.equals("")) {
            String nome = InsertUsuarios.localizar(cod_usuario);
            if (nome != null) {
                codTextField.setEnabled(false);
                nomeTextField.setText(nome);
                resetSenhaButton.setEnabled(true);
            } else {
                JOptionPane.showMessageDialog(null, "Código não encontrado",
                        "Cadastro de Usuários", JOptionPane.ERROR_MESSAGE);
                nomeTextField.setText("");
                codTextField.setText("");
                codTextField.requestFocus();
            }
        }
    }

    public void setCodText(String cod) {
        codTextField.setText(cod);
        carregarUsuario();
    }
    private IDocument doc;
    private MyOwnFocusTraversalPolicy newPolicy;
    private Vector<Component> order = new Vector<Component>(10);
    private MetodosUteis utils = new MetodosUteis();
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buscaCodButton;
    private javax.swing.JLabel cadastroLabel;
    private javax.swing.JTextField cadastroTextField;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JLabel codLabel;
    private javax.swing.JTextField codTextField;
    private javax.swing.JPanel comandosPanel;
    private javax.swing.JPanel contentsPanel;
    private javax.swing.JLabel nomeLabel;
    private javax.swing.JTextField nomeTextField;
    private javax.swing.JCheckBox novoCheckBox;
    private javax.swing.JButton resetSenhaButton;
    private javax.swing.JButton salvarButton;
    // End of variables declaration//GEN-END:variables
}
